from postManager import *
import sqlite3
from utils import cleanhtml
import os
import requests

class ThreadManager:
    def __init__(self, boardName):
        self.posts = []
        self.post_count = 0
        self.current = 0
        self.boardName = boardName
        pass

    def __getitem__(self, key):
        # Subscript operator returns ChanPost object
        return self.posts[key]

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.post_count:
            raise StopIteration
        else:
            self.current += 1
            return self.posts[self.current - 1]

    def __len__(self):
        return self.post_count

    def __str__(self):
        return (
            f"==={self.boardName}===\n" + 
            f"Posts: {self.post_count}"
        )

    def __lt__(self, other):
        return self.post_count < other.post_count
    
    def __le__(self, other):
        return self.post_count <= other.post_count

    def __gt__(self, other):
        return self.post_count > other.post_count
    
    def __ge__(self, other):
        return self.post_count >= other.post_count

    def addPost(self, post):
        # Take a python dict object and append it to the posts array 
        self.posts.append(ChanPost(post))
        self.post_count += 1

    def addPostObject(self, post):
        # Take a ChanPost object and append it to the posts array
        self.posts.append(post)
        self.post_count += 1

    def load(self, matchword="", limit=-1):
        self.posts = []
        self.post_count = 0
        self.current = 0

        conn = sqlite3.connect(os.path.expanduser('~/.meme_magic_stats/database.db'))
        c = conn.cursor()
        sql = f'SELECT * FROM posts WHERE boardname like "{self.boardName}"  LIMIT {limit};'
        values = c.execute(sql)

        for i in values:
            self.posts.append(ChanPost())

            self.posts[self.post_count].postNumber = int(i[0])
            self.posts[self.post_count].comment = i[1]
            self.posts[self.post_count].name = i[2]
            # self.posts[self.post_count].boardName = i[3] Not needed due to board name being stored in the thread manager object
            self.posts[self.post_count].time = int(i[4])
            self.posts[self.post_count].reply_to = int(i[5])
            self.posts[self.post_count].parseImageNameAsString(i[6])
            self.posts[self.post_count].parseExtAsString(i[7])
            self.posts[self.post_count].parseTimAsString(i[8])

            self.post_count += 1
        # print(str(values.rowcount)+" loaded")
        pass

    def save(self):
        # Save the post objects to 'database.db'

        if not os.path.exists(os.path.expanduser('~/.meme_magic_stats')):
            os.makedirs(os.path.expanduser('~/.meme_magic_stats'))

        conn = sqlite3.connect(os.path.expanduser('~/.meme_magic_stats/database.db'))
        c = conn.cursor()
        c.execute(
            """CREATE TABLE IF NOT EXISTS posts (
            no integer, 
            com text, 
            name text,
            boardname text,
            time integer,
            resto integer,
            image_data text,
            ext_data text,
            tim text,
            primary key(no, boardname)) ;"""
        )

        sql = """INSERT INTO posts (
            no, 
            com, 
            name,
            boardname,
            time,
            resto,
            image_data,
            ext_data,
            tim) 
            VALUES(?,?,?,?,?,?,?,?,?)"""

        for i, post in enumerate(self.posts):

            try:
                c.execute(
                    sql,
                    (
                        post.postNumber,
                        post.comment,
                        post.name,
                        self.boardName,
                        post.time,
                        post.reply_to,
                        post.getImageNameAsString(),
                        post.getExtAsString(),
                        post.getTimAsString(),
                    ),
                )
            except:
                pass
        conn.commit()
        conn.close()
        pass

    def getLinks(self):
        # return array of links stored in posts as strings 
        retar = []

        for i in self.posts:
            for f in i.getFileLinks():
                
                if len(f) > 64:
                    retar.append("https://media.8ch.net/file_store/"+f)
                else:
                    retar.append("https://media.8ch.net"+self.boardName+"src/"+f)

        return retar

    def getOriginalPosts(self):
        # return ThreadManager object only containing original posts
        retar = ThreadManager(self.boardName)
        
        for i in self.posts:
            if i.isOP() == "OP":
                retar.addPostObject(i)
        return retar

    def countOccurrenceOfWord(self, word):
        # accept word string and return number of times the word was used across posts 
        retnum = 0

        for i in self.posts:
            retnum += cleanhtml(i.comment).lower().split().count(word.lower())
        return retnum

    def postsFromYear(self, year): 
        # return ThreadManager object with posts from given year
        retar = ThreadManager(self.boardName)

        for i in self.posts:
            if i.year() == year:
                retar.addPostObject(i)
        return retar
    
    def postsFromMonth(self, month):
        # return ThreadManager object with posts from given month
        retar = ThreadManager(self.boardName)

        for i in self.posts:
            if i.month()-1 == month:
                retar.addPostObject(i)
        return retar 
    
    def postsFromDay(self, day):
        # return ThreadManager object with posts from given day
        retar = ThreadManager(self.boardName)

        for i in self.posts:
            if i.day() == day:
                retar.addPostObject(i)
        return retar

    def postsFromHour(self, hour):
        # return ThreadManager object with posts from given hour
        retar = ThreadManager(self.boardName)

        for i in self.posts:
            if i.hour() == hour:
                retar.addPostObject(i)
        return retar

    def postsFromMinute(self, minute):
        # return ThreadManager object with posts from given minute
        retar = ThreadManager(self.boardName)

        for i in self.posts:
            if i.minute() == minute:
                retar.addPostObject(i)
        return retar
    
    def postLengths(self):
        # return array with length of comments
        retar = []

        for i in self.posts:
            retar.append(len(i))
        return retar

    def repliesTo(self, opObject):
        retar = ThreadManager(self.boardName)
        
        for i in self.posts:
            if int(i.reply_to) == int(opObject.postNumber):
                retar.addPostObject(i)

        return retar

    def createThreadsFromOPs(self):
        # takes ThreadManager object, return an array of ThreadMangers seperated by OP
        retar = []

        originalPosts = self.getOriginalPosts()
        
        for originalPost in originalPosts:
            
            threadObject = ThreadManager(self.boardName)
            threadObject.addPostObject(originalPost)
            
            replies = self.repliesTo(originalPost) # return threadmanager

            for reply in replies:
                threadObject.addPostObject(reply)
            retar.append(threadObject)

        return retar

    def downloadFiles(self):
        
        for post in self.posts:
            post.__downloadFiles__(self.boardName)


    def downloadFileType(self, ext):

        for post in self.posts:
            for e in post.ext_data:
                if e == ext:
                    post.__downloadFiles__(self.boardName, ext)